<?php
namespace yan\hkecship;

class EcShipService extends AbstractFactory{
	private $services = [];
    public $environment;
    public $curl;
	protected static $classMap = [
        'postage'=> '\yan\hkecship\factory\Postage',
        'countryList'=> '\yan\hkecship\factory\RegionList',
    ];

    public function __construct()
    {
        $this->services = [];
    }
    protected function getServiceClass($name)
    {
        return \array_key_exists($name, static::$classMap) ? static::$classMap[$name] : null;
    }
    public function __get($name)
    {
        $serviceClass = $this->getServiceClass($name);
        if (null !== $serviceClass) {
            if (!\array_key_exists($name, $this->services)) {
                if(is_array($serviceClass)){
                    if(isset($serviceClass['class'])){
                        $this->services[$name] = $serviceClass['class']::instance();
                    }
                }else{
                    $this->services[$name] = $serviceClass::instance();
                }
            }
            return $this->services[$name];
        }
        return null;
    }
    public function build($config, $sanbox = false){
        $this->environment = new \yan\hkecship\env\Environment($config);
        $this->curl = \yan\hkecship\utils\Curl::instance();
        return $this;
    }
	public function run($data=[], $type = ''){
		$factory = $this->__get($type);
        if(!empty($factory)){
            return $factory->build($this->environment, $this->curl)->run($data);
        }
        return null;
	}

}